package com.lzq.badminton.controller;

import com.alibaba.fastjson.JSONObject;
import com.lzq.badminton.Exception.SystemException;
import com.lzq.badminton.entity.User;
import com.lzq.badminton.enums.AppHttpCodeEnum;
import com.lzq.badminton.service.UserService;
import com.lzq.badminton.utils.SecurityUtils;
import com.lzq.community.domain.dto.LetterSendDto;
import com.lzq.community.domain.vo.NoticeVo;
import com.lzq.community.domain.vo.Pager;
import com.lzq.community.domain.vo.ResponseResult;
import com.lzq.community.util.CommunityConstant;
import com.lzq.community.domain.entity.Message;
import com.lzq.community.service.impl.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@RestController
@RequestMapping("/letter")
public class MessageController implements CommunityConstant {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    // 私信列表
    @GetMapping(path = "/list")
    public ResponseResult getLetterList(int pageNum, int pageSize) {
        User user = userService.getById(SecurityUtils.getUserId());
        // 分页信息
        Pager<Map<String, Object>> page = new Pager<>();
        page.setPage(pageNum);
        page.setSize(5);
        page.setTotal(messageService.findConversationCount(user.getId()));

        // 会话列表
        List<Message> conversationList = messageService.findConversations(
                user.getId(), page.getOffset(), page.getSize());
        List<Map<String, Object>> conversations = new ArrayList<>();
        if (conversationList != null) {
            for (Message message : conversationList) {
                Map<String, Object> map = new HashMap<>();
                map.put("conversation", message);
                map.put("letterCount", messageService.findLetterCount(message.getConversationId()));
                map.put("unreadCount", messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));
                long targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target", userService.getById(targetId));

                conversations.add(map);
            }
        }
        page.setData(conversations);

        // 查询未读消息数量
//        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
//        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);

        return ResponseResult.okResult(page);
    }

    @GetMapping(path = "detail/{conversationId}")
    public ResponseResult getLetterDetail(@PathVariable("conversationId") String conversationId, int pageNum, int pageSize) {
        // 分页信息
        Pager<Map<String, Object>> page = new Pager();
        page.setSize(pageSize);
        page.setTotal(messageService.findLetterCount(conversationId));

        // 私信列表
        List<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getSize());
        List<Map<String, Object>> letters = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", userService.getById(message.getFromId()));
                letters.add(map);
            }
        }

        page.setData(letters);

        Map<String, Object> param = new HashMap<>();
        param.put("letters", letters);
        // 私信目标
        param.put("target", getLetterTarget(conversationId));
        page.setMap(param);




        // 设置已读
        List<Long> ids = getLetterIds(letterList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }

        return ResponseResult.okResult(page);
    }

    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if (SecurityUtils.getUserId() == id0) {
            return userService.getById(id1);
        } else {
            return userService.getById(id0);
        }
    }

    private List<Long> getLetterIds(List<Message> letterList) {
        List<Long> ids = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                if (SecurityUtils.getUserId() == message.getToId() && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }

        return ids;
    }

    @PostMapping(path = "/send")
    public ResponseResult sendLetter(@RequestBody LetterSendDto letterSendDto) {
        User target = userService.findUserByName(letterSendDto.getToName());
        if (target == null) {
            throw new SystemException(AppHttpCodeEnum.TARGET_USER_NOT_EXIT);
        }

        Message message = new Message();
        message.setFromId(SecurityUtils.getUserId());
        message.setToId(target.getId());
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(letterSendDto.getContent());
        message.setCreateTime(new Date());
        messageService.addMessage(message);

        return ResponseResult.okResult();
    }

    @GetMapping(path = "/notice/list")
    public ResponseResult getNoticeList() {
        User user = userService.getById(SecurityUtils.getUserId());
        NoticeVo noticeVo = new NoticeVo();
        // 查询评论类通知
        Message message = messageService.findLatestNotice(user.getId(), TOPIC_COMMENT);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", message);

            String content = message.getContent();
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.getById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("unread", unread);

            noticeVo.setCommentNotice(messageVO);
        }

        // 查询点赞类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_LIKE);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.getById((Long) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_LIKE);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_LIKE);
            messageVO.put("unread", unread);

            noticeVo.setLikeNotice(messageVO);
        }

        // 查询关注类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_FOLLOW);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.getById((Long) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("unread", unread);

            noticeVo.setFollowNotice(messageVO);
        }

        // 查询未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        noticeVo.setLetterUnreadCount(letterUnreadCount);
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        noticeVo.setNoticeUnreadCount(noticeUnreadCount);
        return ResponseResult.okResult(noticeVo);
    }

    @GetMapping(path = "/notice/detail/{topic}")
    public ResponseResult getNoticeDetail(@PathVariable("topic") String topic, int pageNum, int pageSize) {
        User user = userService.getById(SecurityUtils.getUserId());

        Pager<Map<String, Object>> page = new Pager<>();
        page.setSize(pageSize);
        page.setTotal(messageService.findNoticeCount(user.getId(), topic));
        page.setPage(pageNum);

        List<Message> noticeList = messageService.findNotices(user.getId(), topic, page.getOffset(), page.getSize());
        List<Map<String, Object>> noticeVoList = new ArrayList<>();
        if (noticeList != null) {
            for (Message notice : noticeList) {
                Map<String, Object> map = new HashMap<>();
                // 通知
                map.put("notice", notice);
                // 内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user", userService.getById((Long) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));
                // 通知作者
                map.put("fromUser", userService.getById(notice.getFromId()));

                noticeVoList.add(map);
            }
        }

        // 设置已读
        List<Long> ids = getLetterIds(noticeList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }

        return ResponseResult.okResult(page);
    }

}
